<template>
    <el-form-item label="位置搜索" prop="clientId">
      <el-autocomplete
        placeholder="请输入起点"
        v-model="start"
        :fetch-suggestions="handleSearch"
        :trigger-on-focus="false"
        @select="selectedAddressStart"
        value-key="name"
      >
      </el-autocomplete>
      <el-autocomplete
        placeholder="请输入终点"
        v-model="end"
        :fetch-suggestions="handleSearch"
        :trigger-on-focus="false"
        @select="selectedAddressEnd"
        value-key="name"
      >
      </el-autocomplete>
    </el-form-item>
</template>

<script>
export default {
  data() {
    return {
      start: '',
      end: '',
      searchResults: [],
      selectedAddress: null,
      selectObj: {
        start: null,
        end: null,
      }
    };
  },
  methods: {
    selectedAddressStart(item) {
      this.selectObj.start = item;
    },
    selectedAddressEnd(item) {
      this.selectObj.end = item;
      if (this.selectObj.start != null && this.selectObj.end != null) {
        this.$emit('onSelected', this.selectObj);
      }
    },
    handleSearch(queryString, cb) {
      if (queryString === '') {
        this.searchResults = [];
        cb(this.searchResults);
        return;
      }

      const self = this;
      AMap.plugin('AMap.Autocomplete', function () {
        const autoComplete = new AMap.Autocomplete();
        autoComplete.search(queryString, function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            self.searchResults = result.tips;
          } else {
            self.searchResults = [];
          }
          cb(self.searchResults);
        });
      });
    },
  }
};
</script>
<style>
.address-item {
  display: flex;
  justify-content: space-between;
}

.address {
  margin-right: 10px;
}

.city {
  color: gray;
}
</style>
